package io.renren.modules.app.controller;

import io.renren.common.exception.RRException;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddCarInfo;
import io.renren.modules.app.PicSuffix;
import io.renren.modules.app.config.BaiduOCRConfig;
import io.renren.modules.app.config.TencentOCRConfig;
import io.renren.modules.app.config.VehicleOCRConfig;
import io.renren.modules.app.entity.UserCarEntity;
import io.renren.modules.app.entity.UserEntity;
import io.renren.modules.app.entity.VehicleEntity;
import io.renren.modules.app.form.ImgBase64;
import io.renren.modules.app.form.LoginForm;
import io.renren.modules.app.service.UserCarService;
import io.renren.modules.app.service.UserService;
import io.renren.modules.app.utils.JwtUtils;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.Map;

/**
 * @Auther zxl
 * @Date 2018/12/16 17:37
 * @Description 用户
 **/
@RestController
@RequestMapping("/app")
public class AppUserController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    VehicleOCRConfig vehicleOCRConfig;

    @Autowired
    TencentOCRConfig tencentOCRConfig;

    @Autowired
    BaiduOCRConfig baiduOCRConfig;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private UserService userService;

    @Autowired
    private UserCarService userCarService;

    private final ResourceLoader resourceLoader;
    /**
     * 图片路径
     */
    @Value("${check-car.drivePicPath}")
    String drivePicPath;
    @Value("${check-car.orderBeforePicPath}")
    String orderBeforePicPath;
    /**
     * 图片路径
     */
    @Value("${check-car.orderAfterPicPath}")
    String orderAfterPicPath;
    private HttpServletRequest request;
    private String token;

    @Autowired
    public AppUserController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    /**
     * 列表
     * @param params
     * @return
     */
    @GetMapping("/user/list")
    public R list(@RequestParam Map<String, Object> params) {

        PageUtils page = userService.queryPage(params);

        return R.ok().put("page",page);
    }

    /**
     * 查询用户信息
     * @param request
     * @return
     */
    @GetMapping("/check/userInfo")
    public R user(HttpServletRequest request){
        long userId = (Long)request.getAttribute("userId");
        UserEntity user = userService.queryByUserId(userId);
        if (user == null){
            return R.error("用户不存在");
        }else {
            return R.ok().put("data",user);
        }

    }

    /**
     * 用户更改个人信息
     * @param user
     * @param request
     * @return
     */
    @PostMapping("/check/updateUser")
    public R updateUser(@RequestBody UserEntity user,HttpServletRequest request){

        long userId = (Long)request.getAttribute("userId");
        if (user.getMobile()!=null){
            UserEntity userEntity = userService.queryByMobile(user.getMobile());
            if (userEntity != null){
                return R.error("该手机号已注册");
            }
        }else if (StringUtils.isNotBlank(user.getPassword()) ){
            user.setPassword(DigestUtils.sha256Hex(user.getPassword()));
        }
        user.setUserId(userId);
        boolean b = userService.updateUser(user);

        return b ? R.ok() : R.error();

    }

    /**
     * 忘记密码
     * @param loginForm
     * @return
     */
    @PostMapping("/update_pwd")
    public R update_pwd(@RequestBody LoginForm loginForm){

        ValidatorUtils.validateEntity(loginForm);
        UserEntity userEntity = userService.queryByMobile(loginForm.getMobile());
        if (userEntity == null){
            return R.error("用户不存在");
        }
        UserEntity userEntity_update = new UserEntity();
        userEntity_update.setUserId(userEntity.getUserId());
        userEntity_update.setPassword(DigestUtils.sha256Hex(userEntity.getPassword()));
        boolean b = userService.updateUser(userEntity_update);

        return b ? R.ok("修改成功") : R.error();
    }

    /**
     * 查行驶证信息
     * @return
     */
    @GetMapping("/check/user/getCarInfo")
    public R carInfo(HttpServletRequest request){

        long userId = (Long)request.getAttribute("userId");
        UserCarEntity userCarEntity = userCarService.queryOneByUserId(userId);

        if (userCarEntity==null){
            return R.error("请先上传您的行驶证正面照片");
        }
        return R.ok().put("carInfo",userCarEntity).put("userId",userId);
    }

    /**
     * 查行驶证信息
     * post
     * @return
     */
    @PostMapping("/check/user/getCarInfo")
    public R carInfo_post(HttpServletRequest request){

        long userId = (Long)request.getAttribute("userId");
        UserCarEntity userCarEntity = userCarService.queryOneByUserId(userId);

        if (userCarEntity==null){
            return R.error("请先上传您的行驶证正面照片");
        }
        return R.ok().put("carInfo",userCarEntity).put("userId",userId);
    }

    /**
     * 添加修改行驶证信息
     * @param userCarEntity
     * @return
     */
    @PostMapping("/check/user/addUserCar")
    public R addUserCar(@RequestBody UserCarEntity userCarEntity, HttpServletRequest request){

        ValidatorUtils.validateEntity(userCarEntity, AddCarInfo.class);

        long userId = (Long)request.getAttribute("userId");
        String imag_path = drivePicPath+"/"+userId+"_"+userCarEntity.getPlateNum()+PicSuffix.DRIVING_LICENSE_PIC.getSuffix();
        File img_file = new File(imag_path);
        if (!img_file.exists()){
            return R.error("请先上传行驶证照片！");
        }
        UserCarEntity userCar = userCarService.queryOneByUserId(userId);
        if (userCar == null){
            return R.error("请重新上传行驶证信息！");
        }
        userCar.setCarType(userCarEntity.getCarType());
//        userCar.setOperateCar(userCarEntity.getOperateCar());
        userCar.setRegisterDate(userCarEntity.getRegisterDate());
        userCar.setPlateNum(userCarEntity.getPlateNum());
        userCar.setVin(userCarEntity.getVin());

        boolean b = userCarService.update(userCar);
        if (b){
            return R.ok();
        }else {
            return R.error("添加失败");
        }

    }

    /**
     * 上传行驶证照片
     * @param base64
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/check/uploadCarPic")
    public R uploadHP(@RequestBody ImgBase64 base64,
                      HttpServletRequest request) throws Exception {

        System.out.println("到达——--上传照片------"+System.currentTimeMillis());
        System.out.println("base64Data:"+base64.getBase64Data());
        System.out.println("base64Len:"+base64.getBase64Len());
        if (StringUtils.isBlank(base64.getBase64Data())){
            return R.error("内容为空");
        }else  if(base64.getBase64Data().length() != base64.getBase64Len()){
            return R.error("上传数据不全，请重新上传");
        }
        String base64Data = StringUtils.removeStart(base64.getBase64Data(),"data:image/jpeg;base64,");
        base64.setBase64Data(base64Data);
        System.out.println("base64Data:"+base64.getBase64Data());
        System.out.println("base64Data.length:"+base64.getBase64Data().length());
        System.out.println("base64Len:"+base64.getBase64Len());

        BASE64Decoder decoder = new BASE64Decoder();
        byte[] bytes = decoder.decodeBuffer(base64Data);
        long userId = (Long)request.getAttribute("userId");
        String fileName = userId+ PicSuffix.DRIVING_LICENSE_PIC.getSuffix();
        File img_file = new File(drivePicPath+"/"+fileName);
        // 图片压缩
        Thumbnails.of(new ByteArrayInputStream(bytes)).scale(1f).outputQuality(0.7f).toFile(img_file);
        System.out.println("图片压缩完成------"+System.currentTimeMillis());
        logger.info("上传成功,开始解析行驶证........."+System.currentTimeMillis());
        System.out.println("上传成功,开始解析行驶证........."+System.currentTimeMillis());
//         // 阿里云行驶证识别
//        R res = vehicleOCRConfig.ocrImg(drivePicPath+"/"+fileName,"face");

        // 百度云行驶证识别
        R res = baiduOCRConfig.ocr(drivePicPath+"/"+fileName);
        logger.info("行驶证解析成功........."+System.currentTimeMillis());
        System.out.println("上传成功,开始解析行驶证........."+System.currentTimeMillis());
        Integer res_code = (Integer)res.get("code");

        if ( res_code !=200){
            return R.error(res_code,res.get("msg")+",建议直接上传本地照片");
        }
        VehicleEntity vehicleEntity = (VehicleEntity) res.get("data");

        File img = new File(drivePicPath+"/"+fileName);
        if ( vehicleEntity == null || !vehicleEntity.isSuccess()){
            img.delete();
            return R.error("照片识别失败，请重新上传！");

        }
        String use_character = vehicleEntity.getUse_character();
        System.out.println("use_character:"+use_character);
        if (!vehicleEntity.checkplateNum()){
            img.delete();
            return R.error("车牌号错误，请重试！");
        }else if (!vehicleEntity.checkVin()){
            img.delete();
            return R.error("车辆识别代号错误，请重试！");
        }else if(!StringUtils.contains(use_character,"营运")){
            img.delete();
            return R.error("非常抱歉，系统目前只接受使用性质为运营车和非运营车的车辆！");
        }else {
            // 图片重命名
            String new_fileName = userId + "_" + vehicleEntity.getPlate_num() + PicSuffix.DRIVING_LICENSE_PIC.getSuffix();
            img.renameTo(new File(drivePicPath + "/" + new_fileName));
            // 信息入库
            vehicleEntity.setUserId(userId);
            boolean b;
            synchronized (this){

                UserCarEntity userCarEntity = userCarService.queryOneByUserId(userId);
                if (userCarEntity == null) {
                    b = userCarService.insertOne(new UserCarEntity(vehicleEntity));
                } else {
                    b = userCarService.update(new UserCarEntity(vehicleEntity));
                }
            }
            if (b) {
                System.out.println("成功返回："+System.currentTimeMillis());
                return R.ok("上传成功").put("userId", userId)
                        .put("plate_num", vehicleEntity.getPlate_num())
                        .put("vin", vehicleEntity.getVin())
                        .put("register_date", vehicleEntity.getRegister_date())
                        .put("use_character", vehicleEntity.getUse_character());
            }
        }
        System.out.println("上传失败"+System.currentTimeMillis());
        return R.error("上传失败");
    }
    /**
     * 获取行驶证照片
     * @param request
     * @return
     */
    @GetMapping (value = "/showCarPic/{token}",produces = MediaType.IMAGE_JPEG_VALUE)
    public ResponseEntity<?> showHPH5(HttpServletRequest request,
                                    @PathVariable(value = "token") String token) {

        String userId =jwtUtils.getClaimByToken(token).getSubject();

        logger.info("userId:"+userId);

        if (userId == null){
            logger.error("token不能为空");
            return null;
        }
        try {
            return ResponseEntity.ok(resourceLoader.
                    getResource("file:" +drivePicPath+"/"+userId+PicSuffix.DRIVING_LICENSE_PIC.getSuffix() ));
        }catch (Exception e){
            return ResponseEntity.notFound().build();
        }

    }

    /**
     * 获取行驶证照片
     * @param request
     * @return
     */
    @GetMapping (value = "/sms/showCarPic/{userId}/{plate_num}",produces = MediaType.IMAGE_JPEG_VALUE)
    public ResponseEntity<?> showHP(HttpServletRequest request,
                                    @PathVariable(value = "userId",required = true) String userId,
                                    @PathVariable(value = "plate_num",required = true) String plate_num) {

        String image_name = userId+"_"+plate_num+ PicSuffix.DRIVING_LICENSE_PIC.getSuffix();
        System.out.println("image_name:"+image_name);
        try {
            return ResponseEntity.ok(resourceLoader.
                    getResource("file:" +drivePicPath+"/"+image_name ));
        }catch (Exception e){
            return ResponseEntity.notFound().build();
        }

    }

    /**
     * 获取检车前后上传的照片
     * @param request
     * @param userId
     * @param orderId
     * @param type：1：前外；2：前内；3：后外；4：后内
     * @return
     */
    @GetMapping (value = "/showCarPic/{userId}/{orderId}/{type}",produces = MediaType.IMAGE_JPEG_VALUE)
    public ResponseEntity<?> showCarPic(HttpServletRequest request,
                                        @PathVariable(value = "userId") String userId,
                                        @PathVariable(value = "orderId") String orderId,
                                        @PathVariable(value = "type") String type){

        int img_type = Integer.parseInt(type);

        String filename =  userId+"_"+orderId;
        String path="";
        switch (img_type){
            case 1:
                filename = filename+PicSuffix.ORDER_OUTSIDE_PIC.getSuffix();
                path = orderBeforePicPath;
                break;
            case 2:
                filename = filename+PicSuffix.ORDER_INSIDE_PIC.getSuffix();
                path = orderBeforePicPath;
                break;
            case 3:
                filename = filename+PicSuffix.ORDER_OUTSIDE_PIC.getSuffix();
                path = orderAfterPicPath;
                break;
            case 4:
                filename = filename+PicSuffix.ORDER_INSIDE_PIC.getSuffix();
                path = orderAfterPicPath;
                break;
        }
        System.out.println("path:"+path+"/"+filename);
        // 照片不存在
        if (!(new File(path+"/"+filename)).exists()){
            logger.error("照片："+path+"/"+filename+",不存在！");
            return null;
        }
        try{
            return ResponseEntity.ok(resourceLoader.
                    getResource("file:" +path+"/"+filename));
        }catch (RRException e){
            return ResponseEntity.notFound().build();
        }

    }

    @RequestMapping(value = "/*",method = RequestMethod.OPTIONS)
    public ResponseEntity doOptions(){

        return (ResponseEntity) ResponseEntity.noContent();

    }

}
